package art.client.activites;

import art.client.ClientFactory;
import art.client.ClientUtils;
import art.client.places.ArtsListPlace;
import art.client.places.LoginPlace;
import art.client.views.LoginView;
import art.shared.entities.LoginInfo;

import com.google.api.gwt.oauth2.client.Auth;
import com.google.api.gwt.oauth2.client.AuthRequest;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.Callback;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class LoginActivity extends AbstractActivity {

	private final String AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
	private final String CLIENT_ID = "89232749646-lvnc9osrbp1qie6a1c4vrfpga30mfsnr.apps.googleusercontent.com"; // available from the APIs console
	private final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
	private String getEmailUrl = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
	
	private ClientFactory clientFactory = null;

	public LoginActivity(LoginPlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(final AcceptsOneWidget containerWidget, EventBus eventBus) {
		ClientUtils.getUserService().getLoginInfo(
				new AsyncCallback<LoginInfo>() {
					public void onFailure(Throwable error) {
					}

					public void onSuccess(LoginInfo result) {
						if (result == null || !result.isLoggedIn()) {
							LoginView loginView = clientFactory
									.getLoginView(result);
							containerWidget.setWidget(loginView.asWidget());
							loginView.getGoogleLoginButton().addClickHandler(new ClickHandler() {
								
								@Override
								public void onClick(ClickEvent arg0) {
									AuthRequest req = new AuthRequest(AUTH_URL, CLIENT_ID)
								    .withScopes(EMAIL_SCOPE);
									Auth.get().login(req, new Callback<String, Throwable>() {
										
										@Override
										public void onSuccess(String token) {
											getUserEmail(token);
										}
										
										@Override
										public void onFailure(Throwable arg0) {
										}
									});
								}
							});
						} else {
							clientFactory.getPlaceController().goTo(
									new ArtsListPlace("arts", result));
						}
					}
				});
	}

	private void getUserEmail(String token) {
		 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, getEmailUrl + token);

	        try {
	            builder.sendRequest(null, new RequestCallback() {
	                public void onError(Request request, Throwable exception) {
	                    
	                }

	                public void onResponseReceived(Request request, Response response) {
	                	String data = response.getText();
						JSONValue value = JSONParser.parseStrict(data);
	                	JSONValue email = value.isObject().get("email");
	                	
	                	ClientUtils.getUserService().login(email.toString(), new AsyncCallback<LoginInfo>() {

							@Override
							public void onFailure(Throwable arg0) {
							}

							@Override
							public void onSuccess(LoginInfo arg0) {
								clientFactory.getPlaceController().goTo(new LoginPlace("login"));
							}
						});
	                }
	            });

	        } catch (RequestException e) {
	        	
	        }
		
	}

}
